package cn.itcast.dubbo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Hujf
 * @title: DbConfig
 * @description: TODO
 * @date 2020/7/23 0023下午 5:29
 */


@Configuration
@MapperScan("cn.itcast.dubbo.mapper")
public class DbConfig {


    @Bean
    @ConfigurationProperties(prefix = "write.spring.datasource")
    public DataSource writeDataSource() {
        return new DruidDataSource();
    }

    /**
     * @author Hujf
     * @title: writeDataSource
     * @description: TODO
     * @date 2020/7/23 0023下午 3:04
     */

    @Bean
    @ConfigurationProperties(prefix = "read.spring.datasource")
    public DataSource ReadDataSource() {
        return new DruidDataSource();
    }

    @Bean
    @ConfigurationProperties(prefix = "read2.spring.datasource")
    public DataSource ReadDataSource2() {
        return new DruidDataSource();
    }

    @Bean
    @ConfigurationProperties(prefix = "read3.spring.datasource")
    public DataSource ReadDataSource3() {
        return new DruidDataSource();
    }


    @Bean
    public AbstractRoutingDataSource routingDataSource() {
        MyAbstractRoutingDataSource proxy = new MyAbstractRoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>(4);
        targetDataSources.put(DbContextHolder.WRITE, writeDataSource());
        targetDataSources.put(DbContextHolder.READ + "1", ReadDataSource());
        targetDataSources.put(DbContextHolder.READ + "2", ReadDataSource());
        targetDataSources.put(DbContextHolder.READ + "3", ReadDataSource());
        proxy.setDefaultTargetDataSource(writeDataSource());
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }


    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(routingDataSource());
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 实体类对应的位置
        bean.setTypeAliasesPackage("cn.itcast.dubbo.pojo");
        // mybatis的XML的配置
        bean.setMapperLocations(resolver.getResources("classpath:/mapper/*.xml"));
      //  bean.setConfigLocation(resolver.getResource(configLocation));
        return bean.getObject();
    }


}
